#!/usr/bin/env node
import { Command } from 'commander';
import inquirer from 'inquirer';
import chalk from 'chalk';
import { checkPath, downloadTemp, compileTplSync } from './utils.js';
import packageJson from '../package.json' assert { type: 'json' };
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import fsExtra from 'fs-extra';
import { readdirSync, lstatSync } from 'node:fs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const __cmdDir = process.cwd();
const __resolveDir = resolve('./');

console.table([
    {
        command: 'yyds generate|g page|p [name] [page]',
        description: '生成page',
    },
    {
        command: 'yyds generate|g component|c [name] [page]',
        description: '生成component',
    },
    {
        command: 'yyds -h|--help',
        description: '帮助',
    },
    {
        command: 'yyds -v|--version',
        description: '版本',
    },
]);

function inpectCommand(command) {
    console.log(`Called '${command.name()}'`);
    console.log(`args: ${command.args}`);
    console.log('opts: %o', command.opts());
}

const program = new Command('yyds');

program
    .name('yyds')
    .version(packageJson.version, '-v, --version', '版本')
    .option('-t, --trace', 'display extra information when run command')
    .action((options, command) => {
        inpectCommand(command);
    });

program
    .command('new [name]')
    .alias('n')
    .option('-p, --port <number>', 'port number')
    .description('Generate yyds application.')
    .action((name, options, command) => {
        inpectCommand(command);
    });

program
    .command('generate <schematic> [name] [path]')
    .alias('g')
    .description('Generate a yyds element.')
    .action((schematic, name, path, options, command) => {
        inpectCommand(command);

        let tplType;
        if (['page', 'p'].includes(schematic)) {
            tplType = 'page';
        } else if (['component', 'c'].includes(schematic)) {
            tplType = 'component';
        }

        const templateChoices = [];
        const files = readdirSync(resolve(`./src/template/${tplType}`));
        files.forEach(function (item, index) {
            let stat = lstatSync(resolve(`./src/template/${tplType}/${item}`));
            if (stat.isDirectory() === true) {
                templateChoices.push(item);
            }
        });

        //命令行交互工具
        inquirer
            .prompt([
                {
                    type: 'input',
                    name: 'projectName',
                    message: `输入${tplType}名称`,
                    default: name,
                },
                {
                    type: 'input',
                    name: 'savePath',
                    message: `输入保存位置(默认当前文件夹)`,
                    default: path || './',
                },
                {
                    type: 'list',
                    name: 'tplName',
                    message: `选择${tplType}模板`,
                    choices: templateChoices,
                },
            ])
            .then((answers) => {
                const { projectName, tplName, savePath } = answers;
                const tplPath = resolve(__dirname, `template/${tplType}/${tplName}`);
                const targetPath = resolve(`${savePath}/${projectName}`);
                if (checkPath(targetPath)) {
                    console.log('文件已存在,请删除文件后重试');
                    return;
                }

                compileTplSync(tplPath, targetPath, {
                    name: projectName,
                    content: 'content',
                });
            });
    });

program.parse();
